package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.reggie.bean.Emp;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/employee")
public class EmpController {

    @Autowired
    private EmpService empService;

    //登录
    @PostMapping("/login")
    public R<Emp> login(@RequestBody Emp emp, HttpServletRequest request) {
        String username = emp.getUsername();
        String password = emp.getPassword();
        //对密码进行加密（md5加密）
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //创建条件构造器
        QueryWrapper<Emp> wrapper = new QueryWrapper<Emp>();
        wrapper.eq("username", username);
        //查询单个员工
        Emp e = empService.getOne(wrapper);
        //如果查出来的对象为null
        if (e == null) {
            return R.error("登陆失败，用户名不存在");
        }
        //如果查出来了，进行密码比对
        if (!password.equals(e.getPassword())) {
            return R.error("登陆失败，密码错误");
        }
        //查询用户封禁状态
        if (e.getStatus() == 0) {
            return R.error("登陆失败，用户被封禁");
        }
        //将当前登录的用户Id存入Session一份
        request.getSession().setAttribute("empId", e.getId());
        //都通过返回当前登录的用户信息
        return R.success(e);

    }

    //登出
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("empId");
        return R.success("退出成功");
    }

    //分页查员工
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        QueryWrapper<Emp> wrapper = new QueryWrapper<>();
        if (name != null && !name.equals("")) {
            wrapper.like("name", name);
        }
        Page<Emp> pageInfo = new Page<>(page, pageSize);
        empService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }

    //添加员工
    @PostMapping
    public R<String> addEmp(@RequestBody Emp emp) {

        //设置初始密码
        emp.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        return empService.save(emp) ? R.success("添加成功") : R.error("添加失败");
    }

    //根据ID查询信息
    @GetMapping("/{id}")
    public R<Emp> getEmp(@PathVariable("id") Long id) {
        return R.success(empService.getById(id));
    }

    //修改员工
    @PutMapping
    public R<String> updateEmp(@RequestBody Emp emp) {
        return empService.updateById(emp) ? R.success("修改成功") : R.error("修改失败");
    }


}
